package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import net.sf.jsqlparser.expression.LongValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PutMapping;

import java.util.List;

/**
 * @author : jiang
 * @date : 2023/10/20 20:50
 */
@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 新增地址
     * @param addressBook
     */
    @Override
    public void addAddress(AddressBook addressBook) {
        //获取当前操作用户的id
        addressBook.setUserId(BaseContext.getCurrentId());
        //设置当前地址为非默认地址
        addressBook.setIsDefault(0);
        //添加数据到数据库
        addressBookMapper.addAddress(addressBook);
    }

    /**
     * 查询当前登录用户的所有地址信息
     * @return
     */
    @Override
    public List<AddressBook> listAddress() {
        //获取当前用户的id
        Long userId = BaseContext.getCurrentId();
        //查询地址信息
        List<AddressBook> addressBookList = addressBookMapper.list(userId);
        //返回数据
        return addressBookList;
    }

    /**
     * 查询默认地址
     * @return
     */
    @Override
    public AddressBook getDefaultAddress() {
        //获取当前用户的id
        Long userId = BaseContext.getCurrentId();
        //查询当前用户的默认地址
        AddressBook addressBook = addressBookMapper.getDefaultAddress(userId,1);
        return addressBook;
    }

    /**
     * 设置默认地址
     * @param addressBook
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void putDefaultAddress(AddressBook addressBook) {
        //先将用户的所有地址都修改非默认
        addressBook.setIsDefault(0);
        //获取当前用户id
        addressBook.setUserId(BaseContext.getCurrentId());
        //修改当前用户的所有地址
        addressBookMapper.updateAddressByUserId(addressBook);

        //再设置当前地址为默认
        addressBook.setIsDefault(1);
        //修改数据库数据
        addressBookMapper.updateAddressBook(addressBook);
    }

    /**
     * 根据id修改地址
     * @param addressBook
     */
    @Override
    public void updateAddressById(AddressBook addressBook) {
        addressBookMapper.updateAddressBook(addressBook);
    }

    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    @Override
    public AddressBook getAddressById(Long id) {

        AddressBook addressBook = addressBookMapper.getAddressById(id);
        return addressBook;
    }

    /**
     * 根据id删除地址
     * @param addressBook
     */
    @Override
    public void deleteAddressById(AddressBook addressBook) {
        addressBookMapper.delete(addressBook);
    }
}

